<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

require_once APPLICATION_PATH . '/models/Utils/Base.php';

/**
 * Entidad basica la cual provee comportamiento comun a todas las entidades del
 * sistema
 * 
 * @author kristian
 */
abstract class Spalm_Model_Single_BaseEntity extends Spalm_Model_Utils_Base{
    protected $_pk;
    protected $_mapper;


    public function __construct($mapper,array $options = null)
    {
        if (is_array($options)) {
            $this->setOptions($options);
        }

        $this->setMapper($mapper);
    }

    /**
     * Si no se encuentra un atributo se verifica si hay un setter para el mismo
     *
     * @param String $name atributo
     * @param <type> $value valor a asignar
     */
    public function __set($name, $value)
    {
        $method = 'set' . $name;
        if (('mapper' == $name) || !method_exists($this, $method)) {
            throw new Exception('Propiedad invalida');
        }
        $this->$method($value);
    }

    /**
     * Si no se encuentra un atributo se verifica si hay un getter para el mismo
     *
     * @param String $name
     * @return <type> el valor devuelto del getter
     */
    public function __get($name)
    {
        $method = 'get' . $name;
        if (('mapper' == $name) || !method_exists($this, $method)) {
            throw new Exception('Propiedad invalida');
        }
        return $this->$method();
    }

    // completa todos los atributos de una
    /**
     * Completa el modelo mediante un arreglo de datos
     * @param array $options
     * @return BaseEntity
     */
    public function setOptions(array $options)
    {
        $methods = get_class_methods($this);
        
        foreach ($options as $key => $value) {
            $method = 'set' . ucfirst($key);
            if (in_array($method, $methods)) {
                $this->$method($value);
            }
        }
        return $this;
    }


    public function setPK($pk){
        $this->_pk = $pk;
    }

    public function getPK(){
        return $this->_pk;
    }

    public function setMapper($mapper)
    {
        $this->_mapper = $mapper;
        return $this;
    }

    public function getMapper()
    {
        /*
        if (null === $this->_mapper) {
            $this->setMapper($subclaseMapper);
        }
         */
        return $this->_mapper;
    }

    public function save()
    {
        try {
            $this->getMapper()->save($this);
        }
        catch (Zend_Db_Statement_Exception $ex){
            echo $ex->getMessage();
        }
    }

    public function find($id)
    {
        $this->getMapper()->find($id, $this);
        return $this;
    }

    public function fetchAll($where = null)
    {
        return $this->getMapper()->fetchAll($where);
    }

    public function remove(){
        $this->getMapper()->remove($this);
    }

    public abstract function isRemovable();

}
?>
